/**
 * 
 */
package com.study.netty.manyPeopleChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @ClassName: ChatServer
 * @Description: 多人聊天服务器端
 * @author zhuqiang
 * @date 2018年12月27日 下午5:10:00
 */

public class ChatServer {
	private Integer port;

	public ChatServer(int port) {
		this.port = port;
	}

	public void run() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) {
							ChannelPipeline pipeline = ch.pipeline(); // 得到Pipeline
																		// 链
							// 往Pipeline 链中添加一个解码器
							pipeline.addLast("decoder", new StringDecoder());
							// 往Pipeline 链中添加一个编码器
							pipeline.addLast("encoder", new StringEncoder());
							// 往Pipeline 链中添加一个自定义的业务处理对象
							pipeline.addLast("handler", new ChatServerHandler());
						}
					})
					//设置线程队列中等待连接的个数
					.option(ChannelOption.SO_BACKLOG, 128)
					//保持或多连接状态
					.childOption(ChannelOption.SO_KEEPALIVE, true);
			System.out.println("Netty Chat Server 启动......");
			ChannelFuture f = b.bind(port).sync();
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
			System.out.println("Netty Chat Server 关闭......");
		}
	}
	
	public static void main(String[] args) throws Exception {
		new ChatServer(9999).run();
	}
}
